package com.ruoyi.web.controller.TiebaPostCollectGuanzhu.controller;

import java.util.List;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.web.controller.TiebaForums.domain.TiebaForums;
import com.ruoyi.web.controller.TiebaForums.mapper.TiebaForumsMapper;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.vo.PostCollectReq;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.vo.TiebaPostCollectVO;
import com.ruoyi.web.controller.TiebaPosts.domain.TiebaPosts;
import com.ruoyi.web.controller.TiebaPosts.mapper.TiebaPostsMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.domain.TiebaPostCollectGuanzhu;
import com.ruoyi.web.controller.TiebaPostCollectGuanzhu.service.ITiebaPostCollectGuanzhuService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 帖子关注收藏表Controller
 *
 * @author yong
 * @date 2025-04-02
 */
@Api(tags = "用户帖子关注收藏管理")
@RestController
@RequestMapping("/TiebaPostCollectGuanzhu/TiebaPostCollectGuanzhu")
public class TiebaPostCollectGuanzhuController extends BaseController {
    @Autowired
    private ITiebaPostCollectGuanzhuService tiebaPostCollectGuanzhuService;

    @Resource
    private TiebaPostsMapper postsMapper;

    @Resource
    private TiebaForumsMapper tiebaForumsMapper;


    /**
     * 查询帖子关注收藏表列表
     */
    @ApiOperation("查询帖子关注收藏表列表")
    @GetMapping("/list")
    @Anonymous
    public TableDataInfo list(Long forumType) {
        startPage();
        Long userId = getUserId();
        if (forumType == null){
            forumType = 1L;
        }
        List<TiebaPostCollectVO> list = tiebaPostCollectGuanzhuService.getTiebaPostCollectVOList(userId,forumType);
        return getDataTable(list);
    }

    /**
     * 新增帖子关注收藏表
     */
    @ApiOperation("新增帖子关注收藏表")
    @Log(title = "帖子关注收藏表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PostCollectReq postCollectReq) {

        Long userId = getUserId();
        Long postId = postCollectReq.getPostId();

        // 1. 检查帖子是否存在
        TiebaPosts post = postsMapper.selectById(postId);
        if (post == null) {
            return AjaxResult.error("帖子不存在");
        }

        // 2. 查询是否已有记录
        TiebaPostCollectGuanzhu collectGuanzhu = tiebaPostCollectGuanzhuService.getOne(
                new LambdaQueryWrapper<TiebaPostCollectGuanzhu>()
                        .eq(TiebaPostCollectGuanzhu::getUserId, userId)
                        .eq(TiebaPostCollectGuanzhu::getPostId, postId)
        );

        // 3. 存在记录：切换状态
        if (collectGuanzhu != null) {
            int newStatus = collectGuanzhu.getForumType() == 1 ? 2 : 1;
            collectGuanzhu.setForumType(newStatus);
            tiebaPostCollectGuanzhuService.updateById(collectGuanzhu);

            // 通过帖子ID找到对应的贴吧ID
            Long forumId = post.getForumId();
            TiebaForums forum = tiebaForumsMapper.selectById(forumId);

            // 更新贴吧的关注数
            UpdateWrapper<TiebaForums> forumUpdateWrapper = new UpdateWrapper<>();
            if (newStatus == 1) {
                // 关注
                forumUpdateWrapper.setSql("guanzhu_count = guanzhu_count + 1");
            } else {
                // 取消关注
                forumUpdateWrapper.setSql("guanzhu_count = GREATEST(guanzhu_count - 1, 0)");
            }
            forumUpdateWrapper.eq("id", forumId);
            tiebaForumsMapper.update(null, forumUpdateWrapper);

            return AjaxResult.success(newStatus == 1 ? "关注成功" : "取消关注成功");
        }
        // 4. 不存在记录：插入新记录
        else {
            TiebaPostCollectGuanzhu newCollectGuanzhu = new TiebaPostCollectGuanzhu();
            newCollectGuanzhu.setPostId(postId);
            newCollectGuanzhu.setUserId(userId);
            newCollectGuanzhu.setDeptId(getDeptId());
            newCollectGuanzhu.setForumType(postCollectReq.getForumType());

            try {
                boolean saved = tiebaPostCollectGuanzhuService.save(newCollectGuanzhu);

                // 通过帖子ID找到对应的贴吧ID
                Long forumId = post.getForumId();
                TiebaForums forum = tiebaForumsMapper.selectById(forumId);

                // 更新贴吧的关注数
                UpdateWrapper<TiebaForums> forumUpdateWrapper = new UpdateWrapper<>();
                forumUpdateWrapper.setSql("guanzhu_count = guanzhu_count + 1");
                forumUpdateWrapper.eq("id", forumId);
                tiebaForumsMapper.update(null, forumUpdateWrapper);

                if (saved) {
                    return AjaxResult.success(postCollectReq.getForumType() == 1 ? "关注成功" : "收藏成功");
                } else {
                    return AjaxResult.error("操作失败");
                }
            } catch (Exception e) {
                // 处理异常情况
                return AjaxResult.error("操作失败，请稍后再试");
            }
        }
    }


    /**
     * 删除帖子关注收藏表
     */
    @ApiOperation("删除帖子关注收藏表")
    @PreAuthorize("@ss.hasPermi('system:TiebaPostCollectGuanzhu:remove')")
    @Log(title = "帖子关注收藏表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tiebaPostCollectGuanzhuService.removeByIds(Arrays.asList(ids)));
    }
}
